<?php

namespace App\Http\Controllers\Author;

use App\Http\Controllers\Controller;
use App\Services\UploadService;
use Illuminate\Http\Request;

/**
 * 作者上传控制器
 * 
 * 职责：
 * - 处理文件上传相关的HTTP请求
 * - 调用 UploadService 处理业务逻辑
 * - 返回JSON响应
 */
class UploadController extends Controller
{
    /**
     * 上传服务
     * 
     * @var UploadService
     */
    protected UploadService $uploadService;

    /**
     * 构造器
     */
    public function __construct(UploadService $uploadService)
    {
        $this->middleware(['auth']);
        $this->uploadService = $uploadService;
    }

    /**
     * 上传图片
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function image(Request $request)
    {
        // 验证文件是否存在
        if (!$request->hasFile('image')) {
            return response()->json(['error' => '没有上传文件'], 400);
        }

        try {
            // 调用服务层处理上传
            $result = $this->uploadService->uploadImage(
                $request->file('image'),
                auth()->user()
            );

            return response()->json($result);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'error' => '文件验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'error' => '上传失败：' . $e->getMessage()
            ], 500);
        }
    }
} 